package com.woniuxy.shiro;



import com.woniuxy.entity.User;
import com.woniuxy.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;

import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;


import java.util.List;

/**
 * @author zhang
 * @create 2021-07-29-14:39
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {


        return null;
    }


    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行力认证");
        //获取前台账号密码
        UsernamePasswordToken t = (UsernamePasswordToken) token;

        User user = userMapper.getByAccount(t.getUsername());
        if (user == null) {
            throw new UnknownAccountException("账号：" + t.getUsername() + "不存在");
        }
        SecurityUtils.getSubject().getSession().setAttribute("user", user);
        //根据管理员账户定义盐值
//        ByteSource salt = ByteSource.Util.bytes(t.getUsername());
        //getName():UserRealm
        //将返回认证信息中加入盐值
        return new SimpleAuthenticationInfo(user, user.getPassword(),null, getName());


    }

  /*  @Override
    public boolean supports(AuthenticationToken token) {

        return (token instanceof UsernamePasswordToken);
    }*/
}